import { HttpClient } from '@angular/common/http';
import { Component, OnInit, EventEmitter, Output } from '@angular/core';

import { MapService } from '../../core';

@Component({
  selector: 'app-map-tree-control',
  templateUrl: './map-tree-control.component.html',
  styleUrls: ['./map-tree-control.component.scss']
})
export class MapTreeControlComponent implements OnInit {
  glmap = null;
  constructor(
    private http: HttpClient,
    private mapService: MapService,
  ) { }
  defaultKeys: Array<string> = [];
  isLoadedDefaultLayers = false;
  nodes = null;
  private spStyle = null;
  private nodeKeyLayerids = null; // 图层树节点查询图层列表
  @Output() showLegend = new EventEmitter<any>();
  private legends = [];
  ngOnInit() {
    this.getConfig().then((results: any) => {
      this.nodes = results[0];
      this.spStyle = results[1];
      this.nodeKeyLayerids = results[2];
    });
    this.mapService.init().then((mapboxglmap: any) => {
      this.glmap = mapboxglmap;
      if (mapboxglmap.isStyleLoaded() || this.mapService.styleLoaded) {
        this.mapInit();
      } else {
        mapboxglmap.on('load', () => {
          this.mapInit();
        });
      }
    });

  }

  // 地图初始化回调
  mapInit() {
    // 加载默认勾选图层
    this.addSpecialRes().then(() => {
      if (this.defaultKeys.length > 0 && !this.isLoadedDefaultLayers) {
        const layerids = this.getLayerInfoByNodeKey(this.defaultKeys);
        this.showLegends(this.defaultKeys);
        layerids.forEach(key => {
          const layer = this.getLayerStyByKey(key);
          if (!layer) {
            console.log(`未找到${key}对应的图层`);
            return;
          }
          this.addLayer(layer);
        });
        this.isLoadedDefaultLayers = true;
      }
    });
    if (this.defaultKeys.length > 0 && !this.isLoadedDefaultLayers) {
      const layerids = this.getLayerInfoByNodeKey(this.defaultKeys);
      this.showLegends(this.defaultKeys);
      layerids.forEach(key => {
        const layer = this.getLayerStyByKey(key);
        if (!layer) {
          console.log(`未找到${key}对应的图层`);
          return;
        }
        this.addLayer(layer);
      });
      this.isLoadedDefaultLayers = true;
    }
  }

  private addSpecialRes() {
    if (this.spStyle) {
      return this.addImages(this.spStyle.sprite);
    } else {
      this.getSpecialStyle().then(style => {
        return this.addImages(style.sprite);
      });
    }
  }
  // 专题图雪碧图图片资源
  addImages(spritePath) {
    const self = this;
    return this.http.get(`${spritePath}.json`).toPromise().then(spriteJson => {
      const img = new Image();
      img.onload = function () {
        Object.keys(spriteJson).forEach(key => {
          const spriteItem = spriteJson[key];
          const { x, y, width, height } = spriteItem;
          const canvas = self.createCavans(width, height);
          const context = canvas.getContext('2d');
          context.drawImage(img, x, y, width, height, 0, 0, width, height);
          // 单位雪碧图项，转base64字符串
          const base64Url = canvas.toDataURL('image/png');
          self.glmap.loadImage(base64Url, (error, simg) => {
            if (!self.glmap.hasImage(key)) {
              self.glmap.addImage(key, simg);
            }
          });
        });
      };
      img.crossOrigin = 'anonymous';
      img.src = `${spritePath}.png`;
      return 1;
    });
  }
  createCavans(width, height) {
    const canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;
    return canvas;
  }
  // cf-tree默认事件
  loadInitLayers(keys) {
    // 加载默认勾选图层
    this.defaultKeys = keys;
    if (this.glmap && this.glmap.isStyleLoaded() && !this.isLoadedDefaultLayers) {
      const layerids = this.getLayerInfoByNodeKey(this.defaultKeys);
      this.showLegends(this.defaultKeys);
      layerids.forEach(key => {
        const layer = this.getLayerStyByKey(key);
        if (!layer) {
          console.log(`未找到${key}对应的图层`);
          return;
        }
        this.addLayer(layer);
      });
      this.isLoadedDefaultLayers = true;
    }
  }
  /**
   * 根据key获取图层样式
   * @param key ；
   */
  private getLayerStyByKey(key) {
    const layer = this.spStyle.layers.find((layer: any) => {
      return layer.id === key;
    });
    return layer;
  }
  selectLayers(nodekeys) {
    const layerids = this.getLayerInfoByNodeKey(nodekeys);
    this.showLegends(nodekeys);
    layerids.forEach(key => {
      const layer = this.getLayerStyByKey(key);
      if (!layer) {
        console.log(`未找到${key}对应的图层`);
        return;
      }
      this.addLayer(layer);
    });
  }

  removeLayers(keys) {
    const layerids = this.getLayerInfoByNodeKey(keys);
    this.showLegends(keys, 'remove');
    this.mapService.removeLayerByIds(layerids);
  }
  // 显示图例
  showLegends(keys, rtype: 'remove' | 'add' = 'add') {
    const legneds = this.getLayerInfoByNodeKey(keys, 'legend');
    if (rtype === 'add') {
      this.legends.push(...legneds);
    } else {
      this.legends = this.legends.filter(i => {
        return !(legneds.indexOf(i) > -1);
      });
    }
    this.showLegend.emit(this.legends);

  }
  private addLayer(layer) {
    const layersource = this.glmap.getSource(layer.source);
    if (!layersource) {
      this.glmap.addSource(
        layer.source,
        this.spStyle.sources[layer.source]
      );
    }
    if (!layer) { return; }
    if (this.glmap.getLayer(layer.id)) {
      this.mapService.removeLayerByIds([layer.id]);
    }
    this.glmap.addLayer(layer);
  }

  // 获取配置文件
  getConfig() {
    return Promise.all([
      this.getTreeConfig(),
      this.getSpecialStyle(),
      this.getLayerTreeIds()
    ]);
  }
  // 获取树节点对应的图层Ids
  private getLayerInfoByNodeKey(nodeKeys, type: 'id' | 'legend' = 'id') {
    const ids = [];
    const legends = [];
    if (this.nodeKeyLayerids) {
      nodeKeys.forEach(nodekey => {
        const fitem = this.nodeKeyLayerids.find(item => nodekey === item.nodeid);
        if (fitem === undefined) {
          return;
        }
        const layerids = fitem.layerid;
        const legend = fitem.legend;
        ids.push(...layerids);
        if (!Array.isArray(legend)) {
          return;
        }
        legends.push(...legend);

      });
      if (type === 'legend') {
        return legends;
      } else {
        return ids;
      }

    } else {
      console.log('图层树节点-图层ID配置文件未加载！！');
    }
  }

  treeSearch(node) {
  }
  // 图层树配置文件
  private getTreeConfig() {
    return this.mapService.getMapTreeConfig().toPromise()
  }
  // 专题图样式
  private getSpecialStyle() {
    return this.mapService.getMapStyle("mkzWrS9MR")
  }
  // 图层树对应图层ID配置文件
  private getLayerTreeIds() {
    return this.mapService.getLayerTreeIds().toPromise()
  }

  destroy(data) {
    const layerids = this.getLayerInfoByNodeKey(data);
    this.showLegends([]);
    this.mapService.removeLayerByIds(layerids);
  }
}
